﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <summary>
/// zy-新增-HttpRequest请求
/// </summary>
public class HttpRequestHelper
{
    #region Get

    /// <summary>
    /// Get请求
    /// </summary>
    /// <param name="url">请求url</param>
    /// <returns></returns>
    public static string Get(string url)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        req.Timeout = 3000;

        if (req == null) return string.Empty;

        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        using (Stream stream = resp.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
            return reader.ReadToEnd();
    }

    /// <summary>
    /// Get请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="headerKey"></param>
    /// <param name="headerValue"></param>
    /// <returns></returns>
    public static string Get(string url, string headerKey, string headerValue)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        req.Timeout = 3000;
        req.Headers[headerKey] = headerValue;

        if (req == null) return string.Empty;

        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        using (Stream stream = resp.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
            return reader.ReadToEnd();
    }

    #endregion

    #region Post

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="url">接口url</param>
    /// <returns></returns>
    public static string Post(string url)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.Timeout = 3000;

        if (req == null) return string.Empty;

        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        using (Stream stream = resp.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            return reader.ReadToEnd();
    }

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="url">接口url</param>
    /// <param name="postData"></param>
    /// <returns></returns>
    public static string Post(string url, object postData)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/json";
        req.Timeout = 3000;

        if (req == null) return string.Empty;

        byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));
        using (Stream reqStream = req.GetRequestStream())
            reqStream.Write(data, 0, data.Length);
        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        using (Stream stream = resp.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            return reader.ReadToEnd();
    }

    /// <summary>
    /// Post请求（基于raw)
    /// </summary>
    /// <param name="url"></param>
    /// <param name="raw"></param>
    /// <returns></returns>
    public static string Post(string url, string raw)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/json"; // 设置合适的 Content-Type
        request.Timeout = 3000;

        if (request == null) return string.Empty;

        byte[] requestBodyBytes = Encoding.UTF8.GetBytes(raw);
        request.ContentLength = requestBodyBytes.Length;

        using (Stream requestStream = request.GetRequestStream())
            requestStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(responseStream))
            return reader.ReadToEnd();
    }

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="url">接口url</param>
    /// <param name="dic">参数</param>
    /// <returns></returns>
    public static string Post(string url, Dictionary<string, string> dic)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.Timeout = 3000;

        StringBuilder builder = new StringBuilder();
        int i = 0;
        foreach (var item in dic)
        {
            if (i > 0)
                builder.Append("&");
            builder.AppendFormat("{0}={1}", item.Key, item.Value);
            i++;
        }
        byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
        req.ContentLength = data.Length;

        using (Stream reqStream = req.GetRequestStream())
            reqStream.Write(data, 0, data.Length);
        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        using (Stream stream = resp.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            return reader.ReadToEnd();
    }

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="dic"></param>
    /// <param name="headerKey"></param>
    /// <param name="headerValue"></param>
    /// <returns></returns>
    public static string Post(string url, Dictionary<string, string> dic, string headerKey, string headerValue)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.Timeout = 3000;
        req.Headers[headerKey] = headerValue;

        StringBuilder builder = new StringBuilder();
        int i = 0;
        foreach (var item in dic)
        {
            if (i > 0)
                builder.Append("&");
            builder.AppendFormat("{0}={1}", item.Key, item.Value);
            i++;
        }
        byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
        req.ContentLength = data.Length;

        using (Stream reqStream = req.GetRequestStream())
            reqStream.Write(data, 0, data.Length);
        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        using (Stream stream = resp.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            return reader.ReadToEnd();
    }

    #endregion
}

/// <summary>
/// zy-新增-HttpClient异步请求
/// </summary>
public class HttpClientHelperAsync
{
    #region 构造函数

    static HttpClientHelperAsync()
    {
        HttpClientWrapper.Timeout = TimeSpan.FromSeconds(TimeOut);
    }

    private HttpClientHelperAsync() { }

    #endregion

    #region 字段

    private static HttpClient HttpClientWrapper = new HttpClient();

    private static int TimeOut = 3;

    #endregion

    #region Get

    /// <summary>
    /// Get 请求
    /// </summary>
    /// <param name="url">链接</param>
    /// <returns></returns>
    /// <exception cref="TimeoutException"></exception>
    /// <exception cref="Exception"></exception>
    public static async Task<string> Get(string url)
    {
        var response = await HttpClientWrapper.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    /// <summary>
    /// Get 请求（注意 headerValue 只能单行，不能加入换行符等特殊字符）
    /// </summary>
    /// <param name="url">链接</param>
    /// <param name="headerKey">标题key</param>
    /// <param name="headerValue">标题value</param>
    /// <returns></returns>
    /// <exception cref="TimeoutException"></exception>
    /// <exception cref="Exception"></exception>
    public static async Task<string> Get(string url, string headerKey, string headerValue)
    {
        HttpClientWrapper.DefaultRequestHeaders.Clear();
        HttpClientWrapper.DefaultRequestHeaders.Add(headerKey, headerValue);

        var response = await HttpClientWrapper.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    #endregion

    #region Post

    /// <summary>
    /// Post 请求
    /// </summary>
    /// <param name="url">链接</param>
    /// <param name="content">发送内容</param>
    /// <returns></returns>
    public static async Task<string> Post(string url, string content)
    {
        var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
        var response = await HttpClientWrapper.PostAsync(url, httpContent);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    /// <summary>
    /// Post 请求（注意 headerValue 只能单行，不能加入换行符等特殊字符）
    /// </summary>
    /// <param name="url">链接</param>
    /// <param name="content">发送内容</param>
    /// <param name="headerKey">标题key</param>
    /// <param name="headerValue">标题value</param>
    /// <returns></returns>
    /// <exception cref="TimeoutException"></exception>
    /// <exception cref="Exception"></exception>
    public static async Task<string> Post(string url, string content, string headerKey, string headerValue)
    {
        HttpClientWrapper.DefaultRequestHeaders.Clear();
        HttpClientWrapper.DefaultRequestHeaders.Add(headerKey, headerValue);

        var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
        var response = await HttpClientWrapper.PostAsync(url, httpContent);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    /// <summary>
    /// Post 请求（注意 headers 参数只能单行，不能加入换行符等特殊字符）
    /// </summary>
    /// <param name="url">链接</param>
    /// <param name="headers">标题</param>
    /// <param name="content">发送内容</param>
    /// <returns></returns>
    /// <exception cref="TimeoutException"></exception>
    /// <exception cref="Exception"></exception>
    public static async Task<string> Post(string url, string content, Dictionary<string, string> headers)
    {
        HttpClientWrapper.DefaultRequestHeaders.Clear();
        foreach (var header in headers)
            HttpClientWrapper.DefaultRequestHeaders.Add(header.Key, header.Value);

        var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
        var response = await HttpClientWrapper.PostAsync(url, httpContent);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    /// <summary>
    /// Post 请求（注意 headers 参数只能单行，不能加入换行符等特殊字符）
    /// </summary>
    /// <param name="url"></param>
    /// <param name="parameters">参数合集</param>
    /// <param name="headers"></param>
    /// <returns></returns>
    /// <exception cref="TimeoutException"></exception>
    /// <exception cref="Exception"></exception>
    public static async Task<string> Post(string url, Dictionary<string, string> parameters, Dictionary<string, string> headers)
    {
        HttpClientWrapper.DefaultRequestHeaders.Clear();
        foreach (var header in headers)
            HttpClientWrapper.DefaultRequestHeaders.Add(header.Key, header.Value);

        var formContent = new FormUrlEncodedContent(parameters);
        var response = await HttpClientWrapper.PostAsync(url, formContent);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    #endregion
}